from scapy.layers.inet import *
from scapy.layers.tls.all import *

from .packet import PacketRecord

# load_layer('tls')


class TLSPacketRecord(PacketRecord):
    def __init__(self, packet: Packet, mode="b", packet_type="scapy"):
        super().__init__(packet, mode, packet_type)

        self.server_name = ""

        client_hello = packet[TLSClientHello]
        for ext in client_hello.ext:
            if isinstance(ext, TLS_Ext_ServerName):
                # 解析服务器名称指示
                self.server_name = ", ".join(
                    map(lambda name: name.servername.decode(), ext.servernames))

        if not self.server_name:
            raise ValueError()

    def todict(self):
        d = super().todict()
        d.update({
            "Type": "TLS",
            "Host": self.server_name,
            "Url": ""
        })
        return d
